package metr;

import connect.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;

public class StockInFrame extends JFrame {
    private JTable stockInTable;
    private DefaultTableModel tableModel;
    private JComboBox<String> productComboBox;

    public StockInFrame() {
        setTitle("入库管理");
        setSize(800, 600);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());

        // 顶部表单区域
        JPanel formPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        formPanel.setBorder(BorderFactory.createTitledBorder("入库信息"));

        productComboBox = new JComboBox<>();
        loadProducts();

        JTextField quantityField = new JTextField();
        JTextField sourceField = new JTextField();

        formPanel.add(new JLabel("商品:"));
        formPanel.add(productComboBox);
        formPanel.add(new JLabel("入库数量:"));
        formPanel.add(quantityField);
        formPanel.add(new JLabel("入库来源:"));
        formPanel.add(sourceField);

        JButton addBtn = new JButton("添加入库记录");
        formPanel.add(addBtn);

        panel.add(formPanel, BorderLayout.NORTH);

        // 中间表格区域
        tableModel = new DefaultTableModel();
        tableModel.addColumn("入库ID");
        tableModel.addColumn("商品名称");
        tableModel.addColumn("入库时间");
        tableModel.addColumn("入库数量");
        tableModel.addColumn("入库来源");

        stockInTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(stockInTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        add(panel);

        // 加载入库记录
        loadStockInData();

        // 按钮事件
        addBtn.addActionListener(e -> {
            try {
                int selectedIndex = productComboBox.getSelectedIndex();
                if (selectedIndex == -1) {
                    JOptionPane.showMessageDialog(this, "请选择商品", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                int productId = Integer.parseInt(productComboBox.getSelectedItem().toString().split(" - ")[0]);
                int quantity = Integer.parseInt(quantityField.getText().trim());
                String source = sourceField.getText().trim();

                if (quantity <= 0) {
                    JOptionPane.showMessageDialog(this, "入库数量必须大于0", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                try (Connection conn = DBUtil.getConnection()) {
                    // 添加入库记录
                    try (PreparedStatement stmt = conn.prepareStatement(
                            "INSERT INTO stock_in (product_id, in_time, quantity, source) VALUES (?, NOW(), ?, ?)")) {

                        stmt.setInt(1, productId);
                        stmt.setInt(2, quantity);
                        stmt.setString(3, source);
                        stmt.executeUpdate();
                    }

                    // 更新商品库存
                    try (PreparedStatement stmt = conn.prepareStatement(
                            "UPDATE products SET stock_quantity = stock_quantity + ? WHERE product_id = ?")) {

                        stmt.setInt(1, quantity);
                        stmt.setInt(2, productId);
                        stmt.executeUpdate();
                    }

                    JOptionPane.showMessageDialog(this, "入库记录添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    loadStockInData();
                    quantityField.setText("");
                    sourceField.setText("");
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "添加入库记录失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }

    private void loadProducts() {
        productComboBox.removeAllItems();

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT product_id, name FROM products")) {

            while (rs.next()) {
                productComboBox.addItem(rs.getInt("product_id") + " - " + rs.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载商品列表失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void loadStockInData() {
        tableModel.setRowCount(0);

        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(
                     "SELECT s.in_id, p.name, s.in_time, s.quantity, s.source " +
                             "FROM stock_in s JOIN products p ON s.product_id = p.product_id " +
                             "ORDER BY s.in_time DESC")) {

            while (rs.next()) {
                Vector<Object> row = new Vector<>();
                row.add(rs.getInt("in_id"));
                row.add(rs.getString("name"));
                row.add(rs.getTimestamp("in_time"));
                row.add(rs.getInt("quantity"));
                row.add(rs.getString("source"));
                tableModel.addRow(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载入库记录失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}
